Algorithms

1. Linear Search

Step-by-step explanation:

  1. Start from the first element of the array
  2. Compare each element with the target value
  3. If element matches the target, return its index
  4. If end of array is reached without finding target, return -1
Time: O(n)
Space: O(1)

2. Binary Search

Step-by-step explanation:

  1. Array must be sorted
  2. Find the middle element of the array
  3. If middle element equals target, return its index
  4. If target is less than middle, search left half
  5. If target is greater than middle, search right half
  6. Repeat until found or search space is empty
Time: O(log n)
Space: O(1)

3. Bubble Sort

Step-by-step explanation:

  1. Start from the first element
  2. Compare adjacent elements
  3. Swap if they are in wrong order
  4. Repeat for each pair of adjacent elements
  5. Continue passes until no swaps are needed
Time: O(n²)
Space: O(1)

4. Selection Sort

Step-by-step explanation:

  1. Find the minimum element in the unsorted portion
  2. Swap it with the first unsorted element
  3. Move the boundary between sorted and unsorted one element forward
  4. Repeat until entire array is sorted
Time: O(n²)
Space: O(1)

5. Insertion Sort

Step-by-step explanation:

  1. Start with the second element as the key
  2. Compare key with elements in sorted portion
  3. Shift elements greater than key to the right
  4. Insert key in its correct position
  5. Repeat for all elements
Time: O(n²)
Space: O(1)

6. Merge Sort

Step-by-step explanation:

  1. Divide the array into two halves
  2. Recursively sort each half
  3. Merge the two sorted halves
  4. Compare elements from both halves and place smaller one first
  5. Continue until all elements are merged
Time: O(n log n)
Space: O(n)

7. Quick Sort

Step-by-step explanation:

  1. Choose a pivot element
  2. Partition the array around the pivot
  3. Elements less than pivot go to left, greater to right
  4. Recursively apply to left and right partitions
  5. Combine results
Time: O(n log n)
Space: O(log n)

8. Factorial (Recursive)

Step-by-step explanation:

  1. Base case: if n = 0 or 1, return 1
  2. Recursive case: return n * factorial(n-1)
  3. Each recursive call reduces n by 1
  4. Stack builds up until base case is reached
  5. Then stack unwinds, multiplying results
Time: O(n)
Space: O(n)

9. Fibonacci Sequence

Step-by-step explanation:

  1. Base cases: F(0) = 0, F(1) = 1
  2. Recursive case: F(n) = F(n-1) + F(n-2)
  3. Each number is sum of two preceding ones
  4. Sequence: 0, 1, 1, 2, 3, 5, 8, 13, ...
Time: O(2^n)
Space: O(n)

10. Finding Maximum Element

Step-by-step explanation:

  1. Initialize max with first element
  2. Iterate through each element
  3. Compare current element with max
  4. If current element > max, update max
  5. Continue until end of array
  6. Return max value
Time: O(n)
Space: O(1)